package cn.com.idmy.auth.context;

import com.alibaba.fastjson2.JSONObject;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;

public class ThreadLocalContextImpl implements Context {
    private final static ThreadLocal<Long> accountTypeThreadLocal = new InheritableThreadLocal<>();
    private final static ThreadLocal<JSONObject> requestThreadLocal = new InheritableThreadLocal<>();
    private final static ThreadLocal<Map<String, Object>> responseThreadLocal = new InheritableThreadLocal<>();
    private final static ThreadLocal<Map<String, Object>> storageThreadLocal = new InheritableThreadLocal<>();

    public ThreadLocalContextImpl(long accountType) {
        accountTypeThreadLocal.set(accountType);
        requestThreadLocal.set(new JSONObject());
        responseThreadLocal.set(new HashMap<>());
        storageThreadLocal.set(new HashMap<>());
    }

    public static void clear() {
        accountTypeThreadLocal.remove();
        requestThreadLocal.remove();
        responseThreadLocal.remove();
        storageThreadLocal.remove();
    }

    @Override
    public long accountType() {
        return accountTypeThreadLocal.get();
    }

    @Override
    public @NotNull Request request() {
        return new RequestForThreadLocal(requestThreadLocal.get());
    }

    @Override
    public @NotNull Response response() {
        return new ResponseForThreadLocal();
    }

    @Override
    public @NotNull Storage storage() {
        return new StorageForThreadLocal(storageThreadLocal.get());
    }
}
